package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description DishServiceimpl
 * @Author liuqiang
 * @Date 2024/2/19
 */
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Transactional
    @Override
    public void insertDishAndFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        //传输属性
        BeanUtils.copyProperties(dishDTO,dish);
        //向菜品表插入1条信息，需要获得插入的主键值以及自动补充公共字段
        dishMapper.insertDish(dish);
        //获得插入的主键值
        Long dishId = dish.getId();
        //把主键值跟口味信息一一对应
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(fs ->{
                fs.setDishId(dishId);
            });
            //插入口味表n条信息
            dishFlavorMapper.insertDishFlavors(flavors);
        }
    }

    /**
     * 分页查询菜品信息
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        //通过分页插件分页
        //设置分页参数
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        //执行分页查询
        Page<DishVO> dishPage = dishMapper.list(dishPageQueryDTO);
        //返回封装结果
        return new PageResult(dishPage.getTotal(),dishPage.getResult());
    }

    /**
     * 批量删除菜品信息
     * @param ids
     */
    @Transactional
    @Override
    public void deleteDishList(List<Long> ids) {
        //判断菜品的status是否是在售，如果是1不能删除，返回异常，如果是0则删除
        for(Long id : ids){
            Dish dish = dishMapper.getDishById(id);
            //如果是在售则不能删除
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断菜品是否被套餐关联
        //根据ids查询setmeal_dish的setmeal_id是否存在，
        //存在则不能删除，返回异常，如果不存在则删除
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品表中的菜品数据
        for (Long id : ids) {
            dishMapper.deleteDishById(id);
            //删除菜品关联的口味数据
            dishFlavorMapper.deleteDishFlavorByDishId(id);
        }
    }

    /**
     * 根据id查询菜品信息
     * @param id
     * @return
     */
    @Override
    public DishVO getDishById(Long id) {
        DishVO dishVO = new DishVO();
        //根据id查询菜品信息
        Dish dish = dishMapper.getDishById(id);
        //将实体数据传递给VO
        BeanUtils.copyProperties(dish,dishVO);
        //根据dishId查询菜品及其对应的口味信息
        List<DishFlavor> flavors = dishFlavorMapper.listDishFlavorByDishId(id);
        //补充VO缺失的口味数据
        dishVO.setFlavors(flavors);

        return dishVO;
    }

    /**
     * 修改菜品信息和对应的口味信息
     * @param dishDTO
     */
    @Transactional
    @Override
    public void updateDishWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //修改菜品表基本信息
        dishMapper.updateDish(dish);
        //删除原有的口味数据-根据dish_id删除口味信息
        dishFlavorMapper.deleteDishFlavorByDishId(dishDTO.getId());
        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertDishFlavors(flavors);
        }
        //修改购物车表中菜品信息
        shoppingCartMapper.updateCartByDishId(dishDTO);
        //修改套餐菜品关系表中的菜品信息
        setmealDishMapper.updateDishByDishId(dish);
    }

    /**
     * 根据categoryId和name查询菜品信息
     * @param categoryId
     * @param name
     * @return
     */
    @Override
    public List<Dish>getDishByCategoryIdAndName(Long categoryId,String name) {
        List<Dish> dish = dishMapper.getDishByCategoryIdAndName(categoryId,name);
        return dish;
    }

    /**
     * 菜品起售、停售
     * @param status
     * @param id
     */
    @Transactional
    @Override
    public void updateDishStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateDish(dish);
        //菜品停售，则包含菜品的套餐同时停售。
        //判断是否是停售
        if (status == StatusConstant.DISABLE){
            //通过菜品id查询setmeal_dish表中包含菜品id即dish_id的setmeal_id
            List<SetmealDish> setmealDishList = setmealDishMapper.getSetmealDishByDishId(id);
            //停售setmeal_id对应的setmeal中的id
            setmealDishList.forEach(setmealDish -> {
                Setmeal setmeal = Setmeal.builder()
                        .id(setmealDish.getSetmealId())
                        .status(StatusConstant.DISABLE)
                        .build();
                setmealMapper.updateSetmeal(setmeal);
            });
        }
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        //根据categoryId查询菜品信息，这里复用代码
        List<Dish> dishList = dishMapper.getDishByCategoryIdAndName(dish.getCategoryId(),null);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.listDishFlavorByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
